package com.bit.cfdi.web.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.exception.DataException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.bit.cfdi.web.dao.HistorialPasswordDAO;
import com.bit.cfdi.web.domain.HistorialPassword;

@Repository
public class HistorialPasswordDAOImpl extends HibernateDaoSupport implements HistorialPasswordDAO {

	@Autowired
	public void init(final SessionFactory sessionFactory) throws DataAccessException {
		setSessionFactory(sessionFactory);
	}
	
	@Override
	@Transactional public void save(HistorialPassword historialPassword)
			throws DataAccessException {
		getHibernateTemplate().saveOrUpdate(historialPassword);
	}

	@Override
	@Transactional public List<HistorialPassword> getAll() throws DataAccessException {
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional public List<HistorialPassword> getFirstThreeRecords(String email)
			throws DataAccessException {
		if (email != null && !email.isEmpty()) {			
			List<HistorialPassword> usuario = getSession().createQuery(
					"from HistorialPassword as h where h.usuario.email = ? ")
					.setString(0, email).list();	
			return usuario;
		}
		return null;
	}

	@Override
	@Transactional public void deleteMinRecord(HistorialPassword historialPassword)
			throws DataException {
		getHibernateTemplate().delete(historialPassword);
	}

	@Override
	@Transactional public String existThisPassword(String password) throws DataAccessException {
		String email = getHibernateTemplate().find(
				"select password from HistorialPassword as h where h.password = ?", password).toString();
		return email == null ? null : email;
	}



}
